package com.cskaoyan.service;

import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.StatGoodsVo;
import com.cskaoyan.bean.vo.StatOrderVo;
import com.cskaoyan.bean.vo.StatUserVo;
import com.cskaoyan.dao.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cskaoyan.utils.*;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

import java.util.*;

/**
 * @author: lds
 * @clsss: StatisticalServiceImpl
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class StatisticalServiceImpl implements StatisticalService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;


    /**
     * @author: lds
     * @title: queryUser
     * @description: 查询不同天数的注册人数，并按日期升序排列
     * @param: []
     * @return: com.cskaoyan.bean.vo.StatUserVo
     */
    @Override
    public StatUserVo queryUser() {

        UserExample userExample = new UserExample();
        userExample.setOrderByClause("add_time" + " " + "ASC");
        int userNums = 0;
        List<User> users = null;
        try {
            users = userMapper.selectByExample(userExample);
        } catch (Exception e) {
            return null;
        }
        //去重并计数
        users = usertimeTransfor(users);
        HashMap<Date, Integer> dateIntegerHashMap = new HashMap<>();
        for (User user : users) {
            if (dateIntegerHashMap.containsKey(user.getLastLoginTime())) {
                Integer integer = dateIntegerHashMap.get(user.getLastLoginTime());
                integer = integer + 1;
                dateIntegerHashMap.put(user.getLastLoginTime(), integer);
            } else {
                dateIntegerHashMap.put(user.getLastLoginTime(), 1);
            }

        }
        //排序
        TreeSet<StatUserVo.RowsBean> rowsBeansTreeSet = new TreeSet<>(new Comparator<StatUserVo.RowsBean>() {
            @Override
            public int compare(StatUserVo.RowsBean o1, StatUserVo.RowsBean o2) {
                int time = (int) o1.getDay().getTime();
                int time1 = (int) o2.getDay().getTime();
                return time1 - time;
            }
        });
        Set<Date> dates1 = dateIntegerHashMap.keySet();
        Iterator<Date> iterator = dates1.iterator();
        while (iterator.hasNext()) {
            Date date = iterator.next();
            Integer userNum = dateIntegerHashMap.get(date);
            StatUserVo.RowsBean rowsBean = new StatUserVo.RowsBean();
            rowsBean.setUsers(userNum);
            rowsBean.setDay(date);
            rowsBeansTreeSet.add(rowsBean);
        }

        //set然后装到List里面
        ArrayList<StatUserVo.RowsBean> rowsBeans = new ArrayList<>(rowsBeansTreeSet);


        StatUserVo statUserVo = new StatUserVo();
        ArrayList<String> columns = new ArrayList<>();
        columns.add("day");
        columns.add("users");

        statUserVo.setColumns(columns);
        statUserVo.setRows(rowsBeans);
        return statUserVo;
    }

    private List<User> usertimeTransfor(List<User> users) {

        for (User user : users) {

            Date date = DateTransforUtil.dateTransformed(user.getLastLoginTime());
            user.setLastLoginTime(date);
        }
        return users;
    }

    /**
     * @author: lds
     * @title: queryOrder
     * @description: 根据日期查当天的订单总量，下单用户，订单总额，用户平均消费 ,并按日期升序排列
     * @param: []
     * @return: com.cskaoyan.bean.vo.StatOrderVo
     */
    @Override
    public StatOrderVo queryOrder() {


        OrderExample orderExample = new OrderExample();
        orderExample.setOrderByClause("add_time ASC");
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<Order> orders = null;

        try {
            orders = orderMapper.selectByExample(orderExample);
        } catch (Exception e) {
            return null;
        }
        orders = ordertimeTransfor(orders);
        HashMap<Date, List<Order>> dateOrderHashMap = new HashMap<>();


        for (Order order : orders) {
            if (dateOrderHashMap.containsKey(order.getAddTime())) {
                List<Order> orders1 = dateOrderHashMap.get(order.getAddTime());
                orders1.add(order);
            } else {
                List<Order> ordersList = new LinkedList<>();
                ordersList.add(order);
                dateOrderHashMap.put(order.getAddTime(), ordersList);
            }
        }

        //排序
        TreeSet<StatOrderVo.RowsBean> rowsBeansTreeSet = new TreeSet<>(new Comparator<StatOrderVo.RowsBean>() {
            @Override
            public int compare(StatOrderVo.RowsBean o1, StatOrderVo.RowsBean o2) {


                int time = (int) o1.getDay().getTime();
                int time1 = (int) o2.getDay().getTime();
                return time1 - time;
            }
        });


        Set<Date> dates = dateOrderHashMap.keySet();
        Iterator<Date> iterator = dates.iterator();
        while (iterator.hasNext()) {
            Date date = iterator.next();
            List<Order> orders1 = dateOrderHashMap.get(date);
            int size = orders1.size();
            BigDecimal amount = new BigDecimal("0.00");
            LinkedList<Integer> idList = new LinkedList<>();
            for (Order order : orders1) {
                BigDecimal goodsPrice = order.getGoodsPrice();
                amount = amount.add(goodsPrice);
                if (!idList.contains(order.getUserId())) {
                    idList.add(order.getUserId());
                }
            }
            StatOrderVo.RowsBean rowsBean = new StatOrderVo.RowsBean();
            rowsBean.setOrders(size);
            rowsBean.setAmount(amount);
            rowsBean.setCustomers(idList.size());
            rowsBean.setDay(date);
            BigDecimal pcr = amount.divide(new BigDecimal(idList.size()), 2);
            rowsBean.setPcr(pcr);
            rowsBeansTreeSet.add(rowsBean);
        }
        ArrayList<StatOrderVo.RowsBean> rowsBeans = new ArrayList<>(rowsBeansTreeSet);
        ArrayList<String> columns = new ArrayList<>();
        columns.add("day");
        columns.add("orders");
        columns.add("customers");
        columns.add("amount");
        columns.add("pcr");
        StatOrderVo statOrderVo = new StatOrderVo();
        statOrderVo.setColumns(columns);
        statOrderVo.setRows(rowsBeans);
        return statOrderVo;
    }

    private List<Order> ordertimeTransfor(List<Order> orders) {
        for (Order order : orders) {
            Date date = DateTransforUtil.dateTransformed(order.getAddTime());
            order.setAddTime(date);
        }
        return orders;
    }
    /**
     * @author: lds
     * @title: queryGoods
     * @description: 查询不同日期的订单量，下货量，下货总额 ，并按日期升序排列
     * @param: []
     * @return: com.cskaoyan.bean.vo.StatGoodsVo
     */
    @Override
    public StatGoodsVo queryGoods() {

        OrderExample orderExample = new OrderExample();
        orderExample.setOrderByClause("add_time ASC");
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<Order> orders = null;

        try {
            orders = orderMapper.selectByExample(orderExample);
        } catch (Exception e) {
            return null;
        }
        orders = ordertimeTransfor(orders);
        HashMap<Date, List<Order>> dateOrderHashMap = new HashMap<>();

        for (Order order : orders) {
            if (dateOrderHashMap.containsKey(order.getAddTime())) {
                List<Order> orders1 = dateOrderHashMap.get(order.getAddTime());
                orders1.add(order);
            } else {
                List<Order> ordersList = new LinkedList<>();
                ordersList.add(order);
                dateOrderHashMap.put(order.getAddTime(), ordersList);
            }
        }


        //排序
        TreeSet<StatGoodsVo.RowsBean> rowsBeansTreeSet = new TreeSet<>(new Comparator<StatGoodsVo.RowsBean>() {
            @Override
            public int compare(StatGoodsVo.RowsBean o1, StatGoodsVo.RowsBean o2) {


                int time = (int) o1.getDay().getTime();
                int time1 = (int) o2.getDay().getTime();
                return time1 - time;
            }
        });

        Set<Date> dates = dateOrderHashMap.keySet();
        Iterator<Date> iterator = dates.iterator();
        while (iterator.hasNext()) {
            Date date = iterator.next();
            List<Order> orders1 = dateOrderHashMap.get(date);
            int size = orders1.size();
            BigDecimal amount = new BigDecimal("0.00");
            int goodsNum = 0;
            for (Order order : orders1) {
                BigDecimal goodsPrice = order.getGoodsPrice();
                amount = amount.add(goodsPrice);
                goodsNum = queryOrderGoods(order.getId()) + goodsNum;
            }
            StatGoodsVo.RowsBean rowsBean = new StatGoodsVo.RowsBean();
            rowsBean.setOrders(size);
            rowsBean.setAmount(amount);
            rowsBean.setProducts(goodsNum);
            rowsBean.setDay(date);
            rowsBeansTreeSet.add(rowsBean);
        }

        StatGoodsVo statGoodsVo = new StatGoodsVo();
        ArrayList<StatGoodsVo.RowsBean> rowsBeans = new ArrayList<>(rowsBeansTreeSet);
        ArrayList<String> columns = new ArrayList<>();
        columns.add("day");
        columns.add("orders");
        columns.add("products");
        columns.add("amount");
        statGoodsVo.setColumns(columns);
        statGoodsVo.setRows(rowsBeans);
        return statGoodsVo;
    }
    /**
     * @author: lds
     * @title: queryOrderGoods
     * @description: 根据订单id 查询订单货品数量，并按日期升序排列
     * @param: [id]
     * @return: int
     */
    private int queryOrderGoods(Integer id) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(id);
        criteria.andDeletedEqualTo(false);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        int number = orderGoods.get(0).getNumber();
        return number;


    }


}
